package com.zidongxiangxi.clock.server.config;

import com.zidongxiangxi.clock.server.manager.ClockWorkThreadManger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author chenxudong
 * @date 2021/10/09
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class SpringShutdownHook {
    private final ConfigurableApplicationContext configurableApplicationContext;
    private final ClockWorkThreadManger alarmClockWorkThreadManger;

    @PostConstruct
    public void registerShutdownHook() {
        log.info("Register ShutdownHook....");
        Thread shutdownHook = new Thread(() -> {
            try {
                alarmClockWorkThreadManger.stopWorkThread();
                Thread.sleep(8000);
                SpringShutdownHook.this.configurableApplicationContext.close();
                SpringShutdownHook.log.info("ApplicationContext closed, Application shutdown");
            } catch (InterruptedException var2) {
                SpringShutdownHook.log.error(var2.getMessage(), var2);
                Thread.currentThread().interrupt();
            }
        });
        Runtime.getRuntime().addShutdownHook(shutdownHook);
    }
}
